package com.cheyunkeji.er.activity.evaluate;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.cheyun.netsalev3.R;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.adapter.evaluate.BindCarOwnerArchiveAdapter;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.bean.evaluate.CustomerArchiveInfo;
import com.cheyunkeji.er.bean.event.RefreshUIEvent;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.utils.ChannelInfoUtil;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.SwipeLayout;
import com.cheyunkeji.er.view.TopBar;
import com.jeremyliao.liveeventbus.LiveEventBus;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import androidx.lifecycle.Observer;
import butterknife.BindView;
import butterknife.ButterKnife;

public class CarOwnerListActivity extends BaseActivity
    implements OnRefreshListener,
        OnLoadMoreListener,
        BindCarOwnerArchiveAdapter.onItemCBoxRecheckListener,
        AdapterView.OnItemClickListener {

  private static final String TAG = CarOwnerListActivity.class.getSimpleName();

  //    每页数据量
  private static final int COUNTS_PER_PAGE = 10;

  //    搜索关键字
  private String KEY_WORDS = null;

  //    当前列表状态 STATE_REFRESH : 下拉刷新 ，STATE_LOADMORE : 上拉加载更多
  private static int CURRENT_REFRESH_STATE = SwipeLayout.STATE_REFRESH;
  private static int selectedPosition = -1;

  @BindView(R.id.tv_search_content)
  TextView tvSearchContent;

  @BindView(R.id.ll_empty_content_display)
  LinearLayout llEmptyContentDisplay;

  @BindView(R.id.rl_content)
  RelativeLayout rlContent;

  @BindView(R.id.v_topbar)
  TopBar vTopbar;

  @BindView(R.id.swipe_target)
  ListView lvCarownerList;

  @BindView(R.id.activity_car_owner_list)
  LinearLayout activityCarOwnerList;

  @BindView(R.id.swipe_layout)
  SwipeLayout swipeLayout;

  @BindView(R.id.tv_bind_client)
  TextView tvBindClient;

  @BindView(R.id.tv_cancel_close)
  TextView tvCancelClose;
  //     当前页数
  private int CURRENT_LOAD_PAGE = 1;
  private BindCarOwnerArchiveAdapter adapter;
  private ArrayList<CustomerArchiveInfo> dataList;
  private Handler uiRefreshHandler =
      new Handler() {

        @Override
        public void handleMessage(Message msg) {

          if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {

            onRefreshSuccessed((ArrayList<CustomerArchiveInfo>) msg.obj);
          } else {

            onLoadMoreSuccessed((ArrayList<CustomerArchiveInfo>) msg.obj);
          }
        }
      };

  @Override
  protected void init() {
    setContentView(R.layout.er_activity_car_owner_list);
    ButterKnife.bind(this);
    KEY_WORDS = "";
  }

  @Override
  protected void initView() {
    vTopbar.setTitle("车主档案列表");
    vTopbar.setLeftBack();
    vTopbar.setRight("新增", -1, this);
    swipeLayout.setOnRefreshListener(this);
    swipeLayout.setOnLoadMoreListener(this);
    tvBindClient.setOnClickListener(this);
    tvCancelClose.setOnClickListener(this);

    dataList = new ArrayList<>();
    adapter = new BindCarOwnerArchiveAdapter(dataList, this);
    lvCarownerList.setAdapter(adapter);
    lvCarownerList.setOnItemClickListener(this);

    LiveEventBus.get().with("refresh_car_ownerlist",String.class).observe(this, new Observer<String>() {
      @Override
      public void onChanged(String s) {
        KEY_WORDS = "";
      }
    });
  }

  @Override
  protected void initData() {
    KEY_WORDS = getIntent().getStringExtra("USER_NAME");
  }

  @Override
  protected void onResume() {
    super.onResume();
    swipeLayout.setRefreshing(true);
    onRefresh();
  }

  /**
   * 上拉加载成功刷新
   *
   * @param newList
   */
  private void onLoadMoreSuccessed(ArrayList<CustomerArchiveInfo> newList) {
    if (newList != null) {
      if (newList.size() != 0) {
        swipeLayout.endLoadMore();
        dataList.addAll(newList);
        adapter.notifyDataSetChanged();
        CURRENT_LOAD_PAGE++;
      } else {
        swipeLayout.endLoadMore();
        swipeLayout.setLoadMoreEnabled(false);
      }
    }
  }

  private void onRefreshSuccessed(ArrayList<CustomerArchiveInfo> newList) {
    if (newList != null && newList.size() != 0) {
      hideEmptyView();
      dataList.clear();
      dataList.addAll(newList);
      adapter.notifyDataSetChanged();
      CURRENT_LOAD_PAGE++;
    } else if (newList.size() == 0) {
      showContentEmptyView();
      dataList.clear();
      adapter.notifyDataSetChanged();
    }
    swipeLayout.endRefresh();
  }

  private void hideEmptyView() {
    rlContent.setVisibility(View.VISIBLE);
    llEmptyContentDisplay.setVisibility(View.INVISIBLE);
  }

  private void showContentEmptyView() {
    rlContent.setVisibility(View.INVISIBLE);
    if (!TextUtils.isEmpty(KEY_WORDS)) {
      llEmptyContentDisplay.setVisibility(View.VISIBLE);
      tvSearchContent.setText(KEY_WORDS);
    } else {
      llEmptyContentDisplay.setVisibility(View.INVISIBLE);
    }
  }

  /**
   * 加载车主列表
   *
   * @param page
   * @param rows
   * @param keyWords
   */
  public void loadCarOwnerList(int page, int rows, final String keyWords) {
    HashMap<String, String> params = new HashMap<>();
    //      params.put("authkey",
    // UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//
    // params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(),
    // ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
    params.put("page", String.valueOf(page));
    params.put("rows", String.valueOf(rows));
    if (!TextUtils.isEmpty(keyWords)) params.put("keywords", keyWords);
    params.put("channel_id", ChannelInfoUtil.getCurrentChannelInfo().getChannel());

    ApiClient.postForm(
        HttpConstants.ARCHIVE_CUSTOMER_LIST,
        params,
        new RespCallback<List<CustomerArchiveInfo>>() {

          @Override
          protected void onRequestFailed(String msg) {

            SToast.show(msg);
          }

          @Override
          protected void onSuccess(List<CustomerArchiveInfo> data) {

            Log.e(TAG, "onSuccess: " + data.size());
            Log.e(TAG, "onSuccess: CURRENT PAGE INDEX : " + CURRENT_LOAD_PAGE);

            Message msg = uiRefreshHandler.obtainMessage();
            msg.what =
                TextUtils.isEmpty(keyWords)
                    ? SwipeLayout.STATE_NORMAL
                    : SwipeLayout.STATE_SEARCH_BY_KEYWORD;
            msg.obj = data;
            uiRefreshHandler.sendMessage(msg);
          }

          @Override
          public void onError(Exception e) {
            super.onError(e);

            if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {
              swipeLayout.endRefresh();
            } else if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_LOADMORE) {
              swipeLayout.endLoadMore();
            }
          }
        });
  }

  @Override
  public void onRefresh() {
    CURRENT_REFRESH_STATE = SwipeLayout.STATE_REFRESH;
    CURRENT_LOAD_PAGE = 1;
    loadCarOwnerList(CURRENT_LOAD_PAGE, COUNTS_PER_PAGE, KEY_WORDS);
    swipeLayout.setLoadMoreEnabled(true);
  }

  @Override
  public void onLoadMore() {
    CURRENT_REFRESH_STATE = SwipeLayout.STATE_LOADMORE;
    loadCarOwnerList(CURRENT_LOAD_PAGE, COUNTS_PER_PAGE, KEY_WORDS);
  }

  @Override
  public void onItemChecked(int position) {
    selectedPosition = position;
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
      case R.id.tv_bind_client:
        if (selectedPosition != -1) {
          if (null != dataList.get(selectedPosition)) {
            Intent intent = new Intent();
            intent.putExtra("USER_ARCHIVE", dataList.get(selectedPosition));
            setResult(RESULT_OK, intent);
            MyApplication.getInstance().removeActivity(CarOwnerListActivity.class);
            finish();
          }
        } else {
          SToast.show("请绑定客户！", Gravity.CENTER);
        }
        break;
      case R.id.tv_cancel_close:
        MyApplication.getInstance().removeActivity(CarOwnerListActivity.class);
        finish();
        break;
      case R.id.vRight:
        Intent intent = new Intent(this, AddClientActivity.class);
        if (!TextUtils.isEmpty(KEY_WORDS)) intent.putExtra("KEY_WORD", KEY_WORDS);
        startActivity(intent);
        break;
      default:
        break;
    }
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
  }

  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    adapter.setLAST_CHECKED_POSITION(position);
    adapter.notifyDataSetChanged();
  }
}
